//
//  SNKDetailWebController.m
//  SleepNews
//
//  Created by Kavee DJ on 2016/12/10.
//  Copyright © 2016年 Kavee DJ. All rights reserved.
//

#import "SNKDetailWebController.h"
#import "XFLoginViewController.h"
#import "SNKOriginWebController.h"

#import "SNKDataModel.h"
#import "KDJHttpTool.h"
#import "SNKDetailWebModel.h"
#import "SNKDetailImageWebModel.h"
#import "NSDate+SNK.h"
#import "SNKDataBase.h"
#import "MBProgressHUD+Extion.h"
#import "SNKButton.h"

#import <NSDate+DateTools.h>
#import <JavaScriptCore/JavaScriptCore.h>
#import <AVOSCloud.h>
#import <SafariServices/SafariServices.h>

@interface SNKDetailWebController ()<UIWebViewDelegate>

@property (nonatomic, strong) SNKDetailWebModel *detailModel;
@property (nonatomic , weak) UIWebView *webView;
@property (nonatomic, strong) JSContext *jsContext;

@end

@implementation SNKDetailWebController

#pragma mark - Getter and Setter
- (JSContext *)jsContext {
    if (!_jsContext) {
        _jsContext = [[JSContext alloc] init];
    }
    return _jsContext;
}

#pragma mark - Life Cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    [self loadData];
}

- (void)viewWillAppear:(BOOL)animated
{
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}

- (void)setupUI {
    // 重新设置返回按钮
    UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(0, 20, 54, 44)];
    [btn setImage:[UIImage imageNamed:@"night_icon_back"] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(backBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
    
    // 分割线
    UIView *lineV = [[UIView alloc] initWithFrame:CGRectMake(0, 63, SCREENW, 1)];
    lineV.backgroundColor = [UIColor lightGrayColor];
    [self.view addSubview:lineV];
    
    // 收藏
    SNKButton *collectButton = [[SNKButton alloc] initWithFrame:CGRectMake(SCREENW - 44 - 10, 20, 44, 44)];
    [collectButton setImage:[UIImage imageNamed:@"collectButtonBlack"] forState:UIControlStateNormal];
    [collectButton setImage:[UIImage imageNamed:@"CollectBtnSelect"] forState:UIControlStateSelected];
    [collectButton addTarget:self action:@selector(collectBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:collectButton];
    
    if ([[SNKDataBase queryNewsCollectWithDocid:self.dataModel.docid] isEqualToString:@"1"]) {
        collectButton.selected = YES;
    } else {
        [collectButton setTitle:@"收藏" forState:UIControlStateNormal];
    }
    
    // 分享
    UIButton *shareButton = [[UIButton alloc] initWithFrame:CGRectMake(SCREENW - 20 - 88, 20, 44, 44)];
    [shareButton setImage:[UIImage imageNamed:@"shareBtn"] forState:UIControlStateNormal];
    [shareButton addTarget:self action:@selector(share) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:shareButton];
    
    // 网页
    UIWebView *webView = [[UIWebView alloc] initWithFrame:self.view.frame];
    webView.backgroundColor = [UIColor whiteColor];
    webView.kdj_y = 64;
    webView.kdj_height = SCREENH - 64;
    webView.delegate = self;
    [self.view addSubview:webView];
    webView.delegate = self;
    self.webView = webView;
}

- (void)loadData {
    NSString *detailUrl = [NSString stringWithFormat:@"http://c.m.163.com/nc/article/%@/full.html",self.dataModel.docid];
    IMP_BLOCK_SELF(SNKDetailWebController);
    [[KDJHttpTool shareHttpTool] runRequestWithParameters:nil path:detailUrl success:^(id responseObject) {
        block_self.detailModel = [SNKDetailWebModel detailWithDict:responseObject[block_self.dataModel.docid]];
        [block_self showInWebView];
    } failure:^(id error) {
        KLog(@"failure %@",error)
    }];
}

#pragma mark - 本地处理Html
- (void)showInWebView
{
    NSMutableString *html = [NSMutableString string];
    [html appendString:@"<html>"];
    [html appendString:@"<head>"];
    [html appendFormat:@"<link rel=\"stylesheet\" href=\"%@\">",[[NSBundle mainBundle] URLForResource:@"Detail.css" withExtension:nil]];
    [html appendString:@"</head>"];
    
    [html appendString:@"<body>"];
    [html appendString:[self touchBody]];
    [html appendString:@"</body>"];
    
    [html appendString:@"</html>"];
    
    [self.webView loadHTMLString:html baseURL:nil];
    
}

- (NSString *)touchBody
{
    // 处理时间
    NSString *ptimeString = self.dataModel.ptime;
    NSString *fmt = @"YYYY/MM/dd HH:mm:ss";
    NSDate *timeAgoDate = [NSDate dateWithString:ptimeString formatString:fmt];
    
    NSMutableString *body = [NSMutableString string];
    [body appendFormat:@"<div class=\"title\">%@</div>",self.detailModel.title];
    [body appendString:@"<input type=\"button\" class=\"main__button\" value=\"查看原文\"  onclick=\"dealProduct('暂时用不到的参数')\">"];
//    [body appendFormat:@"<a href=%@>查看原文</a>",self.dataModel.url_3w];
    [body appendFormat:@"<div class=\"time\">%@</div>",timeAgoDate.timeAgoSinceNow];
    
    if (self.detailModel.body != nil) {
        [body appendString:self.detailModel.body];
    }
    // 遍历img
    for (SNKDetailImageWebModel *detailImgModel in self.detailModel.img) {
        NSMutableString *imgHtml = [NSMutableString string];
        
        // 设置img的div
        [imgHtml appendString:@"<div class=\"img-parent\">"];
        
        // 数组存放被切割的像素
        NSArray *pixel = [detailImgModel.pixel componentsSeparatedByString:@"*"];
        CGFloat width = [[pixel firstObject] floatValue];
        CGFloat height = [[pixel lastObject] floatValue];
        // 判断是否超过最大宽度
        CGFloat maxWidth = [UIScreen mainScreen].bounds.size.width * 0.96;
        if (width > maxWidth) {
            height = maxWidth / width * height;
            width = maxWidth;
        }
        
        NSString *onload = @"this.onclick = function() {"
        "  window.location.href = 'sx:src=' +this.src;"
        "};";
        
        [imgHtml appendFormat:@"<img onload=\"%@\" width=\"%f\" height=\"%f\" src=\"%@\">",onload,width,height,detailImgModel.src];
        // 结束标记
        [imgHtml appendString:@"</div>"];
        // 替换标记
        [body replaceOccurrencesOfString:detailImgModel.ref withString:imgHtml options:NSCaseInsensitiveSearch range:NSMakeRange(0, body.length)];
    }
    return body;
}

#pragma mark - UIWebView Delegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    NSString *url = request.URL.absoluteString;
    NSRange range = [url rangeOfString:@"sx:src="];
    if (range.location != NSNotFound) {
        NSInteger begin = range.location + range.length;
        NSString *src = [url substringFromIndex:begin];
        [self savePictureToAlbum:src];
        return NO;
    }
    return YES;
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    IMP_BLOCK_SELF(SNKDetailWebController);
    
    self.jsContext = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    self.jsContext.exceptionHandler = ^(JSContext *context, JSValue *exceptionValue) {
        context.exception = exceptionValue;
        NSLog(@"异常信息：%@", exceptionValue);
    };
    
    self.jsContext[@"dealProduct"] = ^(NSString *title){
        //        NSLog(@"返回参数 %@ ",title);
        
        SNKOriginWebController *originVC = [[SNKOriginWebController alloc] init];
        originVC.originUrl = block_self.dataModel.url_3w;
        originVC.title = block_self.dataModel.title;
        [block_self.navigationController pushViewController:originVC animated:YES];
    };
    
}

#pragma mark - Action
- (void)collectBtnClick:(UIButton *)btn {
    
    BOOL isLogin = nil;
    if ([AVUser currentUser].objectId != nil) { // 登录了
        isLogin = YES;
    }else {
        isLogin = NO;
    }
    
    if (isLogin) { // 登录了,才能处理逻辑
        btn.selected = !btn.selected;
        if (btn.selected) {
            [SNKDataBase addNewsWithTitle:self.dataModel.title docid:self.dataModel.docid time:[NSDate currentTime]];
            [MBProgressHUD showSuccess:@"已收藏"];
        }else {
            [SNKDataBase deleteNewsTableWithDocid:self.dataModel.docid];
            [MBProgressHUD showSuccess:@"已取消收藏"];
        }
    } else {
        [self presentViewController:[[XFLoginViewController alloc] init] animated:YES completion:nil];
    }
}

/** 分享 */
- (void)share {

}

// 返回
- (void)backBtnClick {
    [self.navigationController popViewControllerAnimated:YES];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

// 保存到相册方法
- (void)savePictureToAlbum:(NSString *)src
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"确定要保存到相册吗？" preferredStyle:UIAlertControllerStyleActionSheet];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
        
        NSURLCache *cache =[NSURLCache sharedURLCache];
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:src]];
        NSData *imgData = [cache cachedResponseForRequest:request].data;
        UIImage *image = [UIImage imageWithData:imgData];
        UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
        
    }]];
    
    [self presentViewController:alert animated:YES completion:nil];
}


@end
